﻿using SuperCaptcha.Mvc.Globalization;
using SuperCaptcha.Mvc.Processor;
using System.Configuration;
using System.IO;
using System.Reflection;
using System.Web;
using System.Web.Mvc;

namespace SuperCaptcha.Mvc
{
    public class SuperCaptchaController : Controller
    {
        private string _modelStateValidationKey = "SuperCaptchaValidation";
        private string _storageKey = "SuperCaptchaStorage";

        private int CaptchaLength 
        {
            get 
            {
                string length = ConfigurationManager.AppSettings["CaptchaLength"];
                return string.IsNullOrEmpty(length) ? 0 : int.Parse(length);
            }
        }

        public SuperCaptchaController()
        {
            ModelState.Add(_modelStateValidationKey, new ModelState());
        }

        public JsonResult NewCaptcha()
        {
            return Json(new object[] 
            {
                GenerateNewCaptcha() , 
                CaptchaSoundText                
            }, JsonRequestBehavior.AllowGet);
        }

        public JsonResult InitCaptcha()
        {
            return Json(new object[] 
            {
                RefreshImageString,               
                GenerateNewCaptcha(),
                CaptchaSoundText,
                SoundImageString
            }, JsonRequestBehavior.AllowGet);
        }

        public JsonResult ValidateCaptcha(string CaptchaText)
        {
            if (CaptchaText != (string)HttpContext.Cache[_storageKey])
            {                
                ModelState.AddModelError(_modelStateValidationKey, Resource.ResourceManager.GetString("CaptchaCode_Invalid"));
                Response.AddHeader("X-Captcha-Validation", "false");
                return Json(Resource.ResourceManager.GetString("CaptchaCode_Invalid"), JsonRequestBehavior.AllowGet);
            }

            ModelState[_modelStateValidationKey] = new ModelState();
            Response.AddHeader("X-Captcha-Validation", "true");
            return Json(true, JsonRequestBehavior.AllowGet);
        }

        private string GenerateNewCaptcha()
        {
            var captchaCode = LibraryHelper.GenerateRandomCode(CaptchaLength);
            HttpContext.Cache[_storageKey] = captchaCode;

            var processor = new ImageProcessor(captchaCode);
            string newCaptcha = processor.GenerateImage();
            processor.Dispose();
            return newCaptcha;
        }

        private string RefreshImageString
        {
            get
            {
                return ImageString("Content.Images.refresh.png");
            }
        }

        private string SoundImageString
        {
            get
            {
                return ImageString("Content.Images.sound.png");
            }
        }

        private string ImageString(string imageName)
        {
            Assembly assembly = Assembly.GetExecutingAssembly();
            string fileName = string.Format("{0}{1}", assembly.ManifestModule.Name.Replace("dll", string.Empty), imageName);
            Stream image = assembly.GetManifestResourceStream(fileName);
            return image.GetBase64String();
        }

        private string CaptchaSoundText
        {
            get
            {
                var text = (string)HttpContext.Cache[_storageKey];
                return new SoundProcessor().GetSoundBase64String(text);
            }
        }
    }
}
